import subprocess
import threading
import os

from werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple

from jsonrpc import JSONRPCResponseManager, dispatcher

from ast import literal_eval

SIKULI_PATH = 'C:\\sikulix\\'
KAKAO_SIKULI_SCRIPT_PATH = 'kakao.sikuli'

KAKAO_APP_LOCK = threading.Lock()
TIMEOUT = 70
MARKER = '\x01d(^-^)b\x02'


@dispatcher.add_method
def get_latest_upbit_channel_msg(email, passwd):
  lock = KAKAO_APP_LOCK.acquire(timeout=TIMEOUT)
  if not lock:
    return None

  runsikulix_path = os.path.join(SIKULI_PATH, "runsikulix.cmd")
  args = [runsikulix_path, '-r', KAKAO_SIKULI_SCRIPT_PATH, '--', email, passwd]
  try:
    p = subprocess.Popen(args, stdout=subprocess.PIPE)
    p.wait(TIMEOUT)
    output = p.stdout.read()
    output = ''.join(map(chr, output)).strip()
    sidx = output.find(MARKER)
    eidx = output.rfind(MARKER)
    if sidx != -1 and sidx != eidx:
      res = literal_eval(output[sidx + len(MARKER):eidx])
      return res
    else:
      return None
  finally:
    if p is not None and p.poll() is None:
      p.kill()
    KAKAO_APP_LOCK.release()

  return None


@Request.application
def application(request):
  response = JSONRPCResponseManager.handle(request.data, dispatcher)
  return Response(response.json, mimetype='application/json')


if __name__ == '__main__':
  run_simple(hostname='0.0.0.0', port=10101, application=application, threaded=True)
